import 'dart:async';

import 'package:flutter/material.dart';
import 'package:im_module/manager/ImChatManager.dart';
import 'package:im_module/message/type/MessageBody.dart';
import 'package:im_module/message/type/SystemMessageBody.dart';
import 'package:im_module/provider/im_provider.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

class ShowMessageWidget extends StatefulWidget {
  int type;
  String _key;
  String id;
  bool isIm = true; //是否是聊天消息  false 的时候，代表是系统消息或者其他
  ShowMessageWidget(this.type, this._key, this.id, {isIm: true}) {
    this.isIm = isIm;
  }

  @override
  _ShowMessageWidgetState createState() => _ShowMessageWidgetState();
}

class _ShowMessageWidgetState extends State<ShowMessageWidget> {
  ScrollController _scrollController =
      new ScrollController(initialScrollOffset: 0.0);

  int page = 0;
  double tempPosition = 0.0;

  @override
  void initState() {
    super.initState();
    getHistory(null);
  }

  _controllerJumpTo() {
    Timer(Duration(milliseconds: 300), () {
      print("滚动了");
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }

  ///获取历史记录
  void getHistory(String? messageId) {
    ImChatManager()
        .getHistoryMessageList(widget._key, widget.type, widget.id, messageId);
  }

  @override
  Widget build(BuildContext context) {
    print("刷新了消息列表");
    return Consumer<ImProvider>(
      builder: (context, _provider, _) {
        List<V2TimMessage> list = _provider.getHistoryMessage("${widget._key}");

        if (page == 0) {
          _controllerJumpTo();
        } else {
          _scrollController.jumpTo(tempPosition);
          page = 0;
        }
        return Container(
          child: RefreshIndicator(
            onRefresh: () async {
              page = 1;
              String? id = list.first.msgID;
              print("RefreshIndicator->${list.first.toJson()}");

              tempPosition = _scrollController.position.extentInside;

              getHistory(id);
            },
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: MediaQuery.of(context).size.height,
              ),
              child: ListView.builder(
                controller: _scrollController,
                itemCount: list.length,
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  //设置消息已读
                  if (list[index].isRead == false && widget.type == 1) {
                    ImChatManager()
                        .markC2CMessageAsRead(widget.type, widget.id);
                  }

                  //如果是聊天的话，进入聊天消息
                  if (widget.isIm) {
                    bool flag = false;
                    if (index == 0) {
                      flag = true;
                    } else {
                      if (index + 1 != list.length) {
                        int startTime = list[index].timestamp!;
                        int endTime = list[index + 1].timestamp!;

                        if (endTime - startTime < 60) {
                          flag = false;
                        } else {
                          flag = true;
                        }
                      }
                    }
                    return MessageBody(list[index], index, flag);
                  } else {
                    //进入系统消息的内容页面
                    return SystemMessageBody(list[index]);
                  }
                },
              ),
            ),
          ),
        );
      },
    );
  }

  List<MessageBody> getWidget(List<V2TimMessage> list) {
    List<MessageBody> widget = List.empty(growable: true);

    return widget;
  }
}
